<template>
  <div class="ai-chat-container">
    <!-- 聊天头部 -->
    <a-card :bordered="false" class="chat-header-card">
      <div class="chat-header">
        <div class="chat-title">
          <RobotOutlined class="robot-icon" />
          <h3>智能学习助手</h3>
        </div>
        <a-button size="small" class="clear-btn" @click="clearChatHistory">
          <template #icon>
            <DeleteOutlined />
          </template>
          清空对话
        </a-button>
       
      </div>
    </a-card>

    <!-- 聊天内容区域 -->
    <a-card :bordered="false" class="chat-messages-card" :bodyStyle="{ display: 'flex', flexDirection: 'column', height: '100%' }">
      <div class="chat-messages" ref="chatContainer">
        <a-card :bordered="false" v-if="messages.length === 0" class="welcome-card">
          <div class="welcome-message">
            <a-avatar class="robot-avatar">
              <template #icon>
                <RobotOutlined />
              </template>
            </a-avatar>
            <div class="welcome-text">
              <p>你好！我是智能学习助手，有什么可以帮助你的吗？</p>
              <p>你可以问我关于课程、学习方法或平台使用的问题</p>
            </div>
          </div>
        </a-card>

        <!-- 消息列表 -->
        <template v-for="(msg, index) in messages" :key="index">
          <div :class="['message-item-vertical', msg.isUser ? 'user-message-vertical' : 'ai-message-vertical']">
            <a-avatar
              :src="msg.isUser ? userAvatarUrl : undefined"
              class="message-avatar-vertical"
            >
              <template #icon v-if="!msg.isUser">
                <RobotOutlined />
              </template>
            </a-avatar>
            <div class="message-content-vertical">
              <a-bubble 
                :color="msg.isUser ? '#ff4757' : 'transparent'"
                :class="msg.isUser ? 'user-bubble-vertical' : 'ai-bubble-vertical'"
                :style="msg.isUser ? { backgroundColor: 'rgba(255, 71, 87, 0.2)', color: '#fff' } : {}"
              >
                <!-- 用户消息直接显示文本 -->
                <div v-if="msg.isUser" class="message-text">{{ msg.content }}</div>
                <!-- AI消息渲染Markdown -->
                <div v-else-if="msg.isMarkdownRendered" class="message-text markdown-content" v-html="msg.content"></div>
                <!-- AI消息原始内容（未渲染） -->
                <div v-else class="message-text markdown-content" v-html="convertMarkdownToHtml(msg.content)"></div>
              </a-bubble>
              <div class="message-time-vertical">
                {{ formatTime(msg.timestamp) }}
              </div>
            </div>
          </div>
        </template>

        <!-- 加载状态：仅在等待首个分片时显示 -->
        <div v-if="showTyping" class="loading-item-vertical">
          <a-avatar class="message-avatar-vertical">
            <template #icon>
              <RobotOutlined />
            </template>
          </a-avatar>
          <div class="message-content-vertical">
            <a-bubble class="ai-bubble-vertical" :color="'transparent'">
              <a-skeleton active :paragraph="{ rows: 1 }" class="typing-indicator" />
            </a-bubble>
          </div>
        </div>
      </div>
    </a-card>

    <!-- 输入区域 -->
    <a-card :bordered="false" class="chat-input-card">
      <a-form layout="vertical">
        <a-textarea
          v-model:value="inputMessage"
          placeholder="输入你的问题..."
          :auto-size="{ minRows: 2, maxRows: 8 }"
          :max-length="500"
          class="message-input"
          @keydown.enter.prevent="sendMessage"
        />
        <a-form-item class="send-button-container">
          <a-button 
            type="primary" 
            size="large"
            class="send-btn"
            @click="sendMessage"
            :disabled="!inputMessage.trim() || isLoading"
          >
            <template #icon>
              <SendOutlined />
            </template>
            发送
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, computed, onMounted } from 'vue';
import { 
  RobotOutlined, 
  DeleteOutlined, 
  SendOutlined 
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import {searchWithAi,getChat,deleteChat} from "@/api/ai/aiController";
import {searchWithAiStream} from "@/specialApi/aiFetch";
import { useAuthStore } from '@/stores/authStore';
// 尝试不同的marked导入方式
import { marked } from 'marked';
// 备用导入方式
// import marked from 'marked';
// import * as marked from 'marked';
import hljs from 'highlight.js';
import 'highlight.js/styles/github-dark.css';

// 消息类型定义
interface Message {
  content: string;
  isUser: boolean;
  timestamp: Date;
  isMarkdownRendered?: boolean; // 标记是否已渲染为Markdown
}

// 状态管理
const inputMessage = ref('');
const messages = ref<Message[]>([]);
const isLoading = ref(false);
const chatContainer = ref<HTMLDivElement | null>(null);
const authStore = useAuthStore();
// 仅在等待首个分片时显示打字指示器
const hasReceivedFirstChunk = ref(false);
const showTyping = computed(() => {
  return isLoading.value && !hasReceivedFirstChunk.value;
});

// 自动滚动到最新消息
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
    }
  });
};

// 监听消息变化，自动滚动
watch(messages, scrollToBottom, { deep: true });

// 格式化时间显示
const formatTime = (date: Date) => {
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
};

// 与顶部导航一致的头像地址拼接
const getMinioFileUrl = (filePath?: string): string => {
  if (!filePath) {
    return 'https://via.placeholder.com/60x60'
  }
  if (filePath.startsWith('http://') || filePath.startsWith('https://')) {
    return filePath
  }
  const minioUrl = import.meta.env.VITE_MINIO_URL || 'http://172.172.2.99:9000'
  return `${minioUrl}${filePath}`
}

const userAvatarUrl = computed(() => {
  const filePath = authStore.userInfo?.filePath || authStore.userInfo?.avatar
  return getMinioFileUrl(filePath)
});

// 解析后端时间字符串为 Date
const parseServerTime = (timeStr: string): Date => {
  // 将 "YYYY-MM-DD HH:mm:ss" 转为 ISO 近似格式，兼容性更好
  const isoLike = timeStr.replace(' ', 'T');
  const parsed = new Date(isoLike);
  return isNaN(parsed.getTime()) ? new Date() : parsed;
};

// 加载历史聊天记录
const loadHistory = async () => {
  try {
    const history = await getChat();
    if (Array.isArray(history)) {
      messages.value = history.map((item: any) => ({
        content: String(item.content ?? ''),
        isUser: String(item.role ?? '').toLowerCase() === 'user',
        timestamp: parseServerTime(String(item.time ?? '')),
        isMarkdownRendered: false // 历史消息标记为未渲染
      }));
      await nextTick();
      scrollToBottom();
    }
  } catch (e) {
    // 忽略加载历史失败的 UI 打扰，仅在控制台记录
    console.warn('加载历史对话失败', e);
  }
};

onMounted(() => {
  loadHistory();
});

// 发送消息
const sendMessage = async () => {
  const content = inputMessage.value.trim();
  if (!content) return;

  // 添加用户消息
  messages.value.push({
    content,
    isUser: true,
    timestamp: new Date()
  });

  inputMessage.value = '';
  isLoading.value = true;
  hasReceivedFirstChunk.value = false;

  let aiMsgIndex: number | null = null;

  try {
    // 使用异步迭代流式响应
    const stream = await searchWithAiStream({ query: content });
    for await (const chunk of stream) {
      if (!hasReceivedFirstChunk.value) {
        messages.value.push({
          content: chunk,
          isUser: false,
          timestamp: new Date(),
          isMarkdownRendered: false // 新消息标记为未渲染
        });
        aiMsgIndex = messages.value.length - 1;
        hasReceivedFirstChunk.value = true;
      } else if (aiMsgIndex !== null) {
        messages.value[aiMsgIndex].content += chunk;
      }
      await nextTick(); // 确保每次都刷新 UI
      scrollToBottom(); // 逐分片滚动到底部
    }
  } catch (err) {
    if (!hasReceivedFirstChunk.value) {
      messages.value.push({
        content: "请求出错，请稍后再尝试",
        isUser: false,
        timestamp: new Date(),
        isMarkdownRendered: false
      });
    } else if (aiMsgIndex !== null) {
      messages.value[aiMsgIndex].content += "\n[请求出错，请稍后再尝试]";
    }
  } finally {
    isLoading.value = false;
    
    // 消息接收完成后，重新渲染所有AI消息为Markdown格式
    if (aiMsgIndex !== null) {
      reRenderMessageAsMarkdown(aiMsgIndex);
    }
  }
};
//转换markdown
const convertMarkdownToHtml = (markdown: string) => {
  if (!markdown) return '';
  
  try {
    // 预处理Markdown文本，修复各种格式问题
    let processedMarkdown = markdown;
    
    console.log('原始Markdown:', processedMarkdown.substring(0, 200) + '...');
    
    // 1. 修复标题格式：确保 # 后面有空格
    // 匹配 #、##、### 等后面直接跟文字的情况
    processedMarkdown = processedMarkdown.replace(/^(#{1,6})([^#\s])/gm, '$1 $2');
    
    // 2. 修复列表格式：确保 - 后面有空格
    processedMarkdown = processedMarkdown.replace(/^-([^-\s])/gm, '- $1');
    
    // 3. 修复多个连续分隔符，转换为Markdown分割线
    processedMarkdown = processedMarkdown.replace(/^-{3,}/gm, '---');
    
    // 4. 修复邮箱格式：将 undefined 替换为空字符串
    processedMarkdown = processedMarkdown.replace(/undefined/g, '');
    
    // 5. 修复换行问题：确保列表项之间有适当的空行
    processedMarkdown = processedMarkdown.replace(/(\n-)/g, '\n\n-');
    
    // 6. 修复标题和内容之间的格式
    processedMarkdown = processedMarkdown.replace(/(#{1,6}\s+[^\n]+)\n-([^-\n]+)/g, '$1\n\n- $2');
    
    // 7. 修复分割线格式：确保---前后有适当的空行
    processedMarkdown = processedMarkdown.replace(/([^\n])\n-{3,}\n([^\n])/g, '$1\n\n---\n\n$2');
    processedMarkdown = processedMarkdown.replace(/^-{3,}\n([^\n])/g, '---\n\n$1');
    processedMarkdown = processedMarkdown.replace(/([^\n])\n-{3,}$/g, '$1\n\n---');
    
    // 8. 修复---###格式：在---和###之间添加空格
    processedMarkdown = processedMarkdown.replace(/-{3,}(#{1,6})/g, '--- $1');
    
    // 9. 修复###后面丢失空格的情况
    processedMarkdown = processedMarkdown.replace(/(#{1,6})([^#\s\n])/g, '$1 $2');
    
    // 10. 检测到---时让它单独成为一行
    processedMarkdown = processedMarkdown.replace(/([^\n])\n-{3,}([^\n])/g, '$1\n\n---\n\n$2');
    processedMarkdown = processedMarkdown.replace(/([^\n])-{3,}([^\n])/g, '$1\n\n---\n\n$2');
    processedMarkdown = processedMarkdown.replace(/([^\n])-{3,}\n([^\n])/g, '$1\n\n---\n\n$2');
    processedMarkdown = processedMarkdown.replace(/([^\n])\n-{3,}([^\n])/g, '$1\n\n---\n\n$2');
    
    // 11. 确保---前后都有空行
    processedMarkdown = processedMarkdown.replace(/([^\n])\n-{3,}/g, '$1\n\n---');
    processedMarkdown = processedMarkdown.replace(/-{3,}\n([^\n])/g, '---\n\n$1');
    processedMarkdown = processedMarkdown.replace(/-{3,}([^\n])/g, '---\n\n$1');
    
    console.log('预处理后:', processedMarkdown.substring(0, 200) + '...');
    
    // 创建自定义渲染器
    const renderer = new marked.Renderer();
    
    // 处理链接，添加target="_blank"和rel="noopener noreferrer"
    // 新版本marked中，参数可能是对象格式
    renderer.link = (href, title, text) => {
      // 处理href参数，可能是字符串或对象
      let hrefStr = href;
      if (typeof href === 'object' && href !== null) {
        hrefStr = href.href || href.url || String(href);
      } else if (typeof href !== 'string') {
        hrefStr = String(href);
      }
      
      const target = hrefStr && hrefStr.startsWith('http') ? 'target="_blank" rel="noopener noreferrer"' : '';
      const titleAttr = title ? `title="${title}"` : '';
      return `<a href="${hrefStr}" ${target} ${titleAttr}>${text}</a>`;
    };
    
    // 处理图片，添加安全属性
    renderer.image = (href, title, alt) => {
      // 处理href参数，可能是字符串或对象
      let hrefStr = href;
      if (typeof href === 'object' && href !== null) {
        hrefStr = href.href || href.url || String(href);
      } else if (typeof href !== 'string') {
        hrefStr = String(href);
      }
      
      const titleAttr = title ? `title="${title}"` : '';
      return `<img src="${hrefStr}" alt="${alt || ''}" ${titleAttr} loading="lazy" />`;
    };
    
    // 使用marked.parse()方法，这是推荐的用法
    const result = marked.parse(processedMarkdown, {
      renderer: renderer,
      breaks: true,
      gfm: true,
      smartLists: true,
      smartypants: true
    });
    
    console.log('最终HTML:', result.substring(0, 200) + '...');
    
    return result;
    
  } catch (error) {
    console.error('Markdown解析错误:', error);
    console.log('使用备用方案');
    return convertMarkdownSimple(markdown);
  }
};

// 备用Markdown转换函数
const convertMarkdownSimple = (markdown: string) => {
  let result = markdown;
  
  // 预处理文本
  // 1. 修复标题格式
  result = result.replace(/^(#{1,6})([^#\s])/gm, '$1 $2');
  
  // 2. 修复列表格式
  result = result.replace(/^-([^-\s])/gm, '- $1');
  
  // 3. 修复分隔符
  result = result.replace(/^-{3,}/gm, '<hr>');
  
  // 4. 清理undefined
  result = result.replace(/undefined/g, '');
  
  // 5. 处理分割线：确保---前后有适当的空行
  result = result.replace(/([^\n])\n-{3,}\n([^\n])/g, '$1\n\n<hr>\n\n$2');
  result = result.replace(/^-{3,}\n([^\n])/g, '<hr>\n\n$1');
  result = result.replace(/([^\n])\n-{3,}$/g, '$1\n\n<hr>');
  
  // 6. 修复---###格式：在---和###之间添加空格
  result = result.replace(/-{3,}(#{1,6})/g, '<hr> $1');
  
  // 7. 修复###后面丢失空格的情况
  result = result.replace(/(#{1,6})([^#\s\n])/g, '$1 $2');
  
  // 8. 检测到---时让它单独成为一行
  result = result.replace(/([^\n])\n-{3,}([^\n])/g, '$1\n\n<hr>\n\n$2');
  result = result.replace(/([^\n])-{3,}([^\n])/g, '$1\n\n<hr>\n\n$2');
  result = result.replace(/([^\n])\n-{3,}([^\n])/g, '$1\n\n<hr>\n\n$2');
  
  // 9. 确保---前后都有空行
  result = result.replace(/([^\n])\n-{3,}/g, '$1\n\n<hr>');
  result = result.replace(/-{3,}\n([^\n])/g, '<hr>\n\n$1');
  result = result.replace(/-{3,}([^\n])/g, '<hr>\n\n$1');
  
  // 10. 处理标题 (h1-h6)
  result = result.replace(/^(#{1,6})\s+(.+)$/gm, (match, hashes, text) => {
    const level = hashes.length;
    return `<h${level}>${text}</h${level}>`;
  });
  
  // 11. 处理粗体
  result = result.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
  
  // 12. 处理斜体
  result = result.replace(/\*(.*?)\*/g, '<em>$1</em>');
  
  // 13. 处理行内代码
  result = result.replace(/`(.*?)`/g, '<code>$1</code>');
  
  // 14. 处理链接
  result = result.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
  
  // 15. 处理列表项
  result = result.replace(/^- (.+)$/gm, '<li>$1</li>');
  
  // 16. 处理列表组
  result = result.replace(/(<li>.*<\/li>)/gs, '<ul>$1</ul>');
  
  // 17. 处理换行
  result = result.replace(/\n/g, '<br>');
  
  // 18. 清理多余的<br>标签
  result = result.replace(/<br><br>/g, '<br>');
  
  return result;
};



// 重新渲染消息为Markdown格式
const reRenderMessageAsMarkdown = (index: number) => {
  const msg = messages.value[index];
  if (msg.isUser) return; // 只处理AI消息

  try {
    // 转换Markdown为HTML
    const htmlContent = convertMarkdownToHtml(msg.content);
    
    // 使用Vue的响应式系统更新内容
    // 这里我们创建一个新的消息对象来触发Vue的响应式更新
    const updatedMessage = {
      ...msg,
      content: htmlContent,
      isMarkdownRendered: true // 标记为已渲染
    };
    
    // 更新消息数组中的特定消息
    messages.value[index] = updatedMessage;
    
    // 等待DOM更新完成后滚动到底部
    nextTick(() => {
      scrollToBottom();
    });
    
  } catch (error) {
    console.error('重新渲染Markdown失败:', error);
    // 如果渲染失败，保持原始内容
  }
};

// 清空聊天记录
const clearChatHistory = () => {
  if (messages.value.length > 0) {
    deleteChat().then(() => {
      messages.value = [];
      message.success('对话已清空');
      // 重新拉取一次后端记录，确保前后端一致
      loadHistory();
    }).catch(() => {
      message.error('清空对话失败，请稍后再试');
    });
    
  }
};
</script>

<style scoped>
.ai-chat-container {
  background: rgba(15, 52, 96, 0.8);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  height: calc(100vh - 112px); /* 减去导航栏高度 */
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 16px;
  gap: 16px;
}

/* 聊天头部 */
.chat-header-card {
  background: rgba(22, 33, 62, 0.9) !important;
  border: 1px solid rgba(255, 255, 255, 0.15) !important;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.chat-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.robot-icon {
  font-size: 20px;
  color: #ff4757;
}

.chat-title h3 {
  margin: 0;
  color: #fff;
  font-size: 18px;
  font-weight: 600;
}

.clear-btn {
  color: #ddd !important;
  background: transparent !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
}

.clear-btn:hover {
  background: rgba(255, 255, 255, 0.1) !important;
  color: #fff !important;
  border-color: rgba(255, 255, 255, 0.3) !important;
}

.test-separator-btn {
  color: #ffd43b !important;
  background: transparent !important;
  border: 1px solid rgba(255, 212, 59, 0.3) !important;
  margin-left: 8px;
}

.test-separator-btn:hover {
  background: rgba(255, 212, 59, 0.1) !important;
  color: #ffe066 !important;
  border-color: rgba(255, 212, 59, 0.5) !important;
}

.test-missing-space-btn {
  color: #51cf66 !important;
  background: transparent !important;
  border: 1px solid rgba(81, 207, 102, 0.3) !important;
  margin-left: 8px;
}

.test-missing-space-btn:hover {
  background: rgba(81, 207, 102, 0.1) !important;
  color: #69db7c !important;
  border-color: rgba(81, 207, 102, 0.5) !important;
}

.test-separator-alone-btn {
  color: #ff6b6b !important;
  background: transparent !important;
  border: 1px solid rgba(255, 107, 107, 0.3) !important;
  margin-left: 8px;
}

.test-separator-alone-btn:hover {
  background: rgba(255, 107, 107, 0.1) !important;
  color: #ff8e8e !important;
  border-color: rgba(255, 107, 107, 0.5) !important;
}

/* 聊天内容区域 */
.chat-messages-card {
  background: rgba(22, 33, 62, 0.9) !important;
  border: 1px solid rgba(255, 255, 255, 0.15) !important;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

.chat-messages-card :deep(.ant-card-body) {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  min-height: 0;
  overflow-x: hidden; /* 防止横向滚动条 */
}

/* 自定义滚动条 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
}

/* 欢迎消息 */
.welcome-card {
  background: rgba(255, 255, 255, 0.05) !important;
  margin-bottom: 16px;
}

.welcome-message {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 16px;
}

.robot-avatar {
  background: rgba(255, 71, 87, 0.2) !important;
  color: #ff4757 !important;
  border: none !important;
}

.welcome-text {
  color: #ddd;
  line-height: 1.6;
}

.welcome-text p {
  margin: 0 0 8px 0;
}

.welcome-text p:last-child {
  margin-bottom: 0;
}

/* 消息项 */
.message-item {
  display: flex;
  align-items: flex-end;
  margin-bottom: 16px;
  max-width: 85%;
  animation: fadeIn 0.3s ease;
}

.user-message {
  margin-left: auto;
  flex-direction: row-reverse;
}

.ai-message {
  flex-direction: row;
}

.message-avatar {
  width: 40px;
  height: 40px;
  flex-shrink: 0;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  margin: 0 0 0 0; /* 重置默认间距 */
}

.user-message .message-avatar {
  margin-left: 8px;
  margin-right: 0;
}

.ai-message .message-avatar {
  margin-right: 8px;
  margin-left: 0;
}

.message-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.user-message .message-content {
  align-items: flex-end;
}

/* 聊天气泡样式 */
.ai-bubble, .user-bubble {
  min-width: 80px;
  min-height: 40px;
  padding: 12px 16px;
  border-radius: 16px;
  display: inline-block;
  max-width: 100%;
  word-break: break-word;
  overflow-wrap: anywhere;
  box-sizing: border-box;
}

.ai-bubble {
  background: rgba(255, 255, 255, 0.08) !important;
  color: #ddd !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  margin-left: 0;
  margin-right: 0;
}

.user-bubble {
  background: rgba(255, 71, 87, 0.2) !important;
  color: #fff !important;
  border: 1px solid rgba(255, 71, 87, 0.3) !important;
  margin-right: 0;
  margin-left: 0;
}

.message-time {
  margin-top: 4px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.4);
}

.user-message .message-time {
  text-align: right;
}

/* 加载状态 */
.loading-item {
  display: flex;
  margin-bottom: 16px;
  max-width: 85%;
}

.typing-indicator :deep(.ant-skeleton-paragraph) {
  width: 120px !important;
}

/* 输入区域 */
.chat-input-card {
  background: rgba(22, 33, 62, 0.9) !important;
  border: 1px solid rgba(255, 255, 255, 0.15) !important;
}

.message-input {
  background: rgba(255, 255, 255, 0.05) !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  color: #fff !important;
}

.message-input :deep(textarea) {
  background: transparent !important;
  color: #fff !important;
}

.message-input :deep(textarea::placeholder) {
  color: rgba(255, 255, 255, 0.4) !important;
}

.send-button-container {
  display: flex;
  justify-content: flex-end;
  align-items: center; /* 垂直居中按钮 */
  margin-bottom: 0 !important;
  padding: 8px 0; /* 上下留白更美观 */
}

.send-btn {
  background: #ff4757 !important;
  border-color: #ff4757 !important;
  padding: 8px 24px !important;
}

.send-btn:hover, .send-btn:focus {
  background: #ff6b6b !important;
  border-color: #ff6b6b !important;
}

.send-btn:disabled {
  background: rgba(255, 71, 87, 0.5) !important;
  border-color: rgba(255, 71, 87, 0.5) !important;
  cursor: not-allowed !important;
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .message-item {
    max-width: 90%;
  }
  
  .chat-messages {
    padding: 8px;
  }
  
  .ai-chat-container {
    padding: 8px;
    height: calc(100vh - 96px);
  }
  
  .message-item-vertical {
    max-width: 90%;
  }
}

/* 垂直排列的消息项（头像在上，气泡在下） */
.message-item-vertical {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 24px;
  max-width: 80%;
  animation: fadeIn 0.3s ease;
}
.user-message-vertical {
  align-items: flex-end;
  margin-left: auto;
  margin-right: 12px; /* 向中间靠一点 */
}
.ai-message-vertical {
  align-items: flex-start;
  margin-right: auto;
  margin-left: 12px; /* 向中间靠一点 */
}
.message-avatar-vertical {
  width: 40px;
  height: 40px;
  flex-shrink: 0;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  margin-bottom: 8px;
}
.message-content-vertical {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.user-message-vertical .message-content-vertical {
  align-items: flex-end;
  margin-right: 8px; /* 使气泡不完全在头像下方，向中间偏移 */
}
.ai-message-vertical .message-content-vertical {
  margin-left: 8px; /* 使气泡不完全在头像下方，向中间偏移 */
}
.ai-bubble-vertical, .user-bubble-vertical {
  min-width: 80px;
  min-height: 40px;
  padding: 12px 16px;
  border-radius: 16px;
  display: inline-block;
  max-width: 100%;
  word-break: break-word;
  overflow-wrap: anywhere;
  box-sizing: border-box;
}
.ai-bubble-vertical {
  background: rgba(255, 255, 255, 0.08) !important;
  color: #ddd !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
}
.user-bubble-vertical {
  background: rgba(255, 71, 87, 0.2) !important;
  color: #fff !important;
  border: 1px solid rgba(255, 71, 87, 0.3) !important;
}
.message-time-vertical {
  margin-top: 4px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.4);
  width: 100%;
  text-align: left;
}
.user-message-vertical .message-time-vertical {
  text-align: right;
}
.loading-item-vertical {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 24px;
  max-width: 60%;
}

/* 深度覆盖，确保任何库样式不会阻止换行 */
.ai-bubble-vertical :deep(pre),
.user-bubble-vertical :deep(pre),
.ai-bubble :deep(pre),
.user-bubble :deep(pre) {
  white-space: pre-wrap !important;
  word-break: break-word !important;
  overflow-wrap: anywhere !important;
  hyphens: auto;
}

/* Markdown内容样式 */
.markdown-content {
  line-height: 1.6;
  color: #ddd;
}

.markdown-content :deep(h1),
.markdown-content :deep(h2),
.markdown-content :deep(h3),
.markdown-content :deep(h4),
.markdown-content :deep(h5),
.markdown-content :deep(h6) {
  color: #fff;
  margin: 16px 0 8px 0;
  font-weight: 600;
}

.markdown-content :deep(h1) { font-size: 1.5em; }
.markdown-content :deep(h2) { font-size: 1.3em; }
.markdown-content :deep(h3) { font-size: 1.1em; }

.markdown-content :deep(p) {
  margin: 8px 0;
}

.markdown-content :deep(strong) {
  color: #fff;
  font-weight: 600;
}

.markdown-content :deep(em) {
  color: #ddd;
  font-style: italic;
}

.markdown-content :deep(code) {
  background: rgba(255, 255, 255, 0.1);
  color: #ff6b6b;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 0.9em;
}

.markdown-content :deep(pre) {
  background: rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  padding: 12px;
  margin: 12px 0;
  overflow-x: auto;
}

.markdown-content :deep(pre code) {
  background: transparent;
  color: #ddd;
  padding: 0;
  border-radius: 0;
}

/* 代码高亮样式覆盖 */
.markdown-content :deep(.hljs) {
  background: rgba(0, 0, 0, 0.4) !important;
  color: #ddd !important;
  border-radius: 4px;
}

.markdown-content :deep(.hljs-keyword) {
  color: #ff6b6b !important;
}

.markdown-content :deep(.hljs-string) {
  color: #51cf66 !important;
}

.markdown-content :deep(.hljs-number) {
  color: #ffd43b !important;
}

.markdown-content :deep(.hljs-comment) {
  color: #868e96 !important;
  font-style: italic;
}

.markdown-content :deep(.hljs-function) {
  color: #74c0fc !important;
}

.markdown-content :deep(blockquote) {
  border-left: 4px solid #ff4757;
  margin: 12px 0;
  padding: 8px 16px;
  background: rgba(255, 71, 87, 0.1);
  border-radius: 0 6px 6px 0;
}

.markdown-content :deep(ul),
.markdown-content :deep(ol) {
  margin: 8px 0;
  padding-left: 24px;
}

.markdown-content :deep(li) {
  margin: 4px 0;
}

.markdown-content :deep(a) {
  color: #ff6b6b;
  text-decoration: none;
  border-bottom: 1px solid transparent;
  transition: all 0.3s ease;
}

.markdown-content :deep(a:hover) {
  color: #ff8e8e;
  border-bottom-color: #ff6b6b;
}

.markdown-content :deep(a:visited) {
  color: #ff8e8e;
}

.markdown-content :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 12px 0;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  overflow: hidden;
}

.markdown-content :deep(th),
.markdown-content :deep(td) {
  border: 1px solid rgba(255, 255, 255, 0.1);
  padding: 8px 12px;
  text-align: left;
}

.markdown-content :deep(th) {
  background: rgba(255, 71, 87, 0.2);
  color: #fff;
  font-weight: 600;
}

.markdown-content :deep(td) {
  color: #ddd;
}

.markdown-content :deep(hr) {
  border: none;
  border-top: 1px solid rgba(255, 255, 255, 0.2);
  margin: 16px 0;
  height: 1px;
  background: linear-gradient(to right, transparent, rgba(255, 255, 255, 0.2), transparent);
}

.markdown-content :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 6px;
  margin: 8px 0;
}

/* 确保链接在新标签页中打开 */
.markdown-content :deep(a[href^="http"]::after) {
  content: " ↗";
  font-size: 0.8em;
  opacity: 0.7;
}
</style>
